package cn.ctvonline.android.kaopu.widget.view;

/**
 * Created by dujian on 15/12/10.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

public class ScaleableImageView extends ImageView {
    static final String TAG = ScaleableImageView.class + "";
    private int width, height;
    private Bitmap bitmap;
    private float pX, pY;

    public ScaleableImageView(Context context) {
        this(context, null);
    }

    public ScaleableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        this.bitmap = bm;
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        pX = (float) width / 2;
        pY = (float) height / 2;
    }

    @Override
    public void setBackground(Drawable background) {
        this.bitmap = ((BitmapDrawable) background).getBitmap();
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        pX = (float) width / 2;
        pY = (float) height / 2;
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        this.bitmap = ((BitmapDrawable) drawable).getBitmap();
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        pX = (float) width / 2;
        pY = (float) height / 2;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int nWidth = (int) (width * scaleRate);
        int nHeight = (int) (height * scaleRate);
        Log.i(TAG, "nWidth=" + nWidth + ",nHeight=" + nHeight);
        Matrix matrix = new Matrix();
        matrix.setScale(scaleRate, scaleRate, pX, pY);
        Bitmap newBmp = Bitmap.createScaledBitmap(bitmap, nWidth, nHeight, true);
        canvas.drawBitmap(newBmp, matrix, null);
        matrix.reset();
    }

    float scaleRate = 1f;

    public void scale(float scaleRate) {
        if (scaleRate > 2) {
            return;
        }
        this.scaleRate = scaleRate;
        invalidate();
    }
}
